﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using NPOI.XWPF.UserModel;

namespace Jiuyong
{
	/// <summary>
	/// CodeDocumentationPage.xaml 的交互逻辑
	/// </summary>
	public partial class CodeDocumentationPage : Page
	{
		public CodeDocumentationPage()
		{
			InitializeComponent();
			Loaded += Page_Loaded;
		}

		private void Page_Loaded(object sender, RoutedEventArgs e)
		{
			this.BindCommand(MediaCommands.Play, RunDocumentation);
		}

		private void RunDocumentation(object sender, ExecutedRoutedEventArgs e)
		{
			ToDocumentation(@"D:\FCYM\CQAB\src\RoadFlow\", $@"T:/tmp/cqab_code_all_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.docx");
		}

		string includExts = ".cs|.aspx|.cshtml|.sln|.csproj|.config|.sql";
		string SkipPaths = @"\bin|\.vs";
		/// <summary>
		/// 用于路径排除规则的分割字符集。
		/// </summary>
		private const string SkipPathSeparator = ";,，；|\r\n";

		private void ToDocumentation(string source, string outputFile)
		{

			XWPFDocument doc = new XWPFDocument();      //创建新的word文档

			//XWPFParagraph p1 = doc.CreateParagraph();   //向新文档中添加段落
			//p1.Alignment = ParagraphAlignment.CENTER; //段落对其方式为居中

			//XWPFRun r1 = p1.CreateRun();                //向该段落中添加文字
			//r1.SetText("测试段落一");

			//XWPFParagraph p2 = doc.CreateParagraph();
			//p2.Alignment = ParagraphAlignment.LEFT;

			//XWPFRun r2 = p2.CreateRun();
			//r2.SetText("测试段落二");

			var fAll = Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories);
			var fExts = includExts.Split(SkipPathSeparator.ToCharArray());
			var pSkips = SkipPaths.Split(SkipPathSeparator.ToCharArray());
			var fs = from f in fAll
					 where fExts.Any(y => f.EndsWith(y))
					 && !pSkips.Any(y => f.Contains(y))
					 select f;

			//var dfs = fs.ToArray();
			//fs = fs.Take(10);

			var fc = 0;//文件计数。
			var cc = 0;//字符总计。
			var lc = 0;//有效行数。
			var alc = 0;//总行数。

			foreach (var f in fs)
			{

				var f1 = f.Substring(source.Length);
				var fileContents = File.ReadAllLines(f);
				var fileLineCount = fileContents.Count(x => !String.IsNullOrWhiteSpace(x));
				var fileLength = fileContents.Sum(x => x.Length);

				//标题。
				var P = doc.CreateParagraph();
				P.Alignment = ParagraphAlignment.LEFT;
				var title = P.CreateRun();
				title.SetBold(true);
				var br = BreakType.TEXTWRAPPING;
				title.AddBreak(br);
				title.AppendText($"文件：{f1}");
				title.AddBreak(br);
				title.AppendText($"{fileLineCount}个有效行");
				title.AddBreak(br);
				title.AppendText($"{fileLength}个字符");
				//title.AddBreak(br);
				//title.SetText($"文件：{f1}\n{fileLineCount}行\n{fileLength}字\n");
				//title.AddBreak(br);

				var content = P.CreateRun();
				foreach (var line in fileContents)
				{
					content.AddBreak(br);
					content.AppendText(line);
				}

				Console.WriteLine($"{++fc:####,####} {fileLineCount:####}行 {fileLength:####,####} 字，文件：{f}");
				cc += fileLength;
				lc += fileLineCount;
				alc += fileContents.Length;
				//nfs.Add(f3);

				//文件内容替换。f->f3
				//var dir = System.IO.Path.GetDirectoryName(f3);
				//if (Directory.Exists(dir))
				//{
				//}
				//else
				//{
				//	Directory.CreateDirectory(dir);
				//}
				//File.WriteAllBytes(f3, c1);
				//OutputLine(f3);
				//Items.Add(f3);
			}
			var v1 = alc;//总行数（包括无效空白行）。
			Console.WriteLine($"共计 {fc} 个文件 {lc}有效行 {cc:####万####} 字。");


			//保存文件。
			FileStream sw = File.Create(outputFile); //...
			doc.Write(sw);                              //...
			sw.Close();                                 //在服务端生成文件
			Console.WriteLine($"文件已经成功写入“{outputFile}”中。");

		}

	}

	public partial class CodeDocumentationViewModel : ViewModelBase
	{
	}
}
